
export const createDiv = (text: string, ...clzs: string[]) => {
    const ele = document.createElement('div');
    ele.innerText = text;
    ele.classList.add(...clzs);
    return ele;
}

interface MTEvent {
    clientX: number,
    clientY: number,
}

export class MoveableDialog {

    protected btnClose = createDiv('', 'close_btn');
    protected dialog = createDiv('', 'dialog', 'flex_col');

    readonly show = () => {
        this.btnClose.onclick = () => {
            this.close();    
        }
        this.dialog.classList.add('dialog_show');

        this.dialog.addEventListener('touchend', this.onMouseUp);
        this.dialog.addEventListener('mouseup', this.onMouseUp);

        this.dialog.addEventListener('touchstart', this.onMouseDown);
        this.dialog.addEventListener('mousedown', this.onMouseDown);

        this.dialog.addEventListener('touchmove', this.onMouseMove);
        this.dialog.addEventListener('mousemove', this.onMouseMove);
        document.body.appendChild(this.dialog);
    }

    readonly close = () => {
        if (this.closeFlag) {
            return;
        }
        this.closeFlag = true;
        this.dialog.classList.remove('dialog_show');
        this.dialog.offsetWidth;
        this.dialog.classList.add('dialog_close');
        this.dialog.addEventListener('animationend', ()=>{
            document.body.removeChild(this.dialog);
        });
    }

    private closeFlag = false;
    private dragFlag = false;
    private offsetX = 0;
    private offsetY = 0;

    private readonly onMouseDown = (event: MouseEvent | TouchEvent) => {
        let e: MTEvent = {
            clientX: 0,
            clientY: 0,
        }
        if (event instanceof TouchEvent) {
            e = event.touches[0];
        } else {
            e = event;
        }
        this.dragFlag = true;
        const rect = this.dialog.getBoundingClientRect();
        this.offsetX = e.clientX - (rect.left + rect.width / 2);
        this.offsetY = e.clientY - (rect.top + rect.height / 2);
    }

    private readonly onMouseMove = (event: MouseEvent | TouchEvent) => {
        if (!this.dragFlag) {
            return;
        }
        let e: MTEvent = {
            clientX: 0,
            clientY: 0,
        }

        if (event instanceof TouchEvent) {
            e = event.touches[0];
        } else {
            e = event;
        }

        const x = e.clientX - this.offsetX;
        const y = e.clientY - this.offsetY;
        this.dialog.style.left = `${x}px`;
        this.dialog.style.top = `${y}px`;
    }

    private readonly onMouseUp = (_: MouseEvent | TouchEvent) => {
        this.dragFlag = false;
    }
}
